<?php

/**
 * Created by PhpStorm.
 * User: qiliping
 * Date: 2016/12/20
 * Time: 下午2:31
 */
class Wxopen extends CI_Controller
{
    /**
     * 授权事件接收URL”每隔10分钟接收component_verify_ticket
     */
    function callback(){
        require_once('third_party/wxBizMsgCrypt.php');
        $this->load->model('Syswxconfig_model');

        $wxconfig = $this->Syswxconfig_model->get_wxconfig();
        //http://center.weyowo.com/wxopen/callback?encrypt_type=aes &timestamp=1438521627 &nonce=33431792 &msg_signature=xxxxxx &signature=xxxxxxx

            //$this->Syswxconfig->update_verify_ticket($wxconfig['appid'],time(),'test','000');


        $timeStamp    = $this->input->get('timestamp');
        $nonce        = $this->input->get('nonce');
        $encrypt_type = $this->input->get('encrypt_type');
        $msg_sign     = $this->input->get('msg_signature');
        $encryptMsg   = file_get_contents('php://input');
        //fdc3c98079a649f6dec75abba07379a8weyowo20168
        $wx = new WXBizMsgCrypt('deanxinyun', 'fec3c98079a649f6daxc75abba07379a8deanxin175', $wxconfig['appid']);

        /*$this->Syswxconfig->update_verify_ticket('wx23430c06a7fd6523',time(),'执行成功',$msg_sign);
        echo "success";
        return;*/

        /**开始解密*/
        $xml_tree = new DOMDocument();
        $xml_tree->loadXML($encryptMsg);
        $array_e = $xml_tree->getElementsByTagName('Encrypt');

        $encrypt = $array_e->item(0)->nodeValue;

        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $from_xml = sprintf($format, $encrypt);


        $msg_xml = '';//解密后的原文，当return返回0时有效

        $errCode = $wx->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg_xml);




        if ($errCode == 0){
//            $componentVerifyTicket = $this->parse_xml($msg_xml,'Encrypt');
            $xml = new \DOMDocument();
            $xml->loadXML($msg_xml);
            $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
            $component_verify_ticket = $array_e->item(0)->nodeValue;

            $this->Syswxconfig_model->update_verify_ticket(time(),$component_verify_ticket,$encrypt_type);
        }else{
            $this->Syswxconfig_model->update_verify_ticket(time(),'错了',$errCode);
        }
        echo "success";
        return;
    }






    /**
     * 获取消息
     * @param $appid
     */
    function get_msg($appid){
        print_r($appid);
    }
}